package com.wangcang.widgetlibrary.activity.wxapi;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.bean.ActiveEntryOrStoreHouseRes;
import com.wangcang.widgetlibrary.bean.WeChatBean;
import com.wangcang.widgetlibrary.tools.LogUtils;
import com.wangcang.widgetlibrary.tools.PayUtil;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Response;

import java.util.HashMap;

import static com.tencent.mm.sdk.modelbase.BaseResp.ErrCode.ERR_OK;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXPayEntryActivity";

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_result);
        api = WXAPIFactory.createWXAPI(this, "wxb716f229c6313a0e");
        api.handleIntent(getIntent(), this);
        paySuccess();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        ///第四步
        Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getResources().getString(R.string.app_tip));
            if (resp.errCode == ERR_OK) {
                paySuccess();
                return;
            } else if (resp.errCode == -1) {
                builder.setMessage(getResources().getString(R.string.app_fail_pay) + resp.errCode);
                builder.setNegativeButton(getResources().getString(R.string.app_return), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        api.unregisterApp();
                        api.detach();
                        api.handleIntent(getIntent(), null);
                    }
                });
            } else if (resp.errCode == -2) {
                builder.setMessage(getResources().getString(R.string.app_drop_pay) + resp.errCode);
                builder.setNegativeButton(getResources().getString(R.string.app_return), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        api.unregisterApp();
                        api.detach();
                        api.handleIntent(getIntent(), null);
                    }
                });
            }

            AlertDialog alertDialog = builder.create();

            alertDialog.setCanceledOnTouchOutside(false);//设置触摸对话框的外侧区域，不取消对话框
            alertDialog.show();
            //有dialog的情况下，返回键的监听
            alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        finish();
                    }
                    return false;
                }
            });
        }
    }


    OnResponseListener<String> onResponseListener = new OnResponseListener<String>() {
        @Override
        public void onStart(int what) {

        }

        @Override
        public void onSucceed(int what, Response<String> response) {
            try {
                ActiveEntryOrStoreHouseRes activeEntryOrStoreHouseRes = JSON.parseObject(response.get(), ActiveEntryOrStoreHouseRes.class);
                if ("0".equals(activeEntryOrStoreHouseRes.code)) {
                    finish();
                } else if ("4".equals(activeEntryOrStoreHouseRes.code)) {
                    finish();
                }
            } catch (Exception e) {
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {
            Toast.makeText(WXPayEntryActivity.this, response.get() + "网络请求进入onFailed方法", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFinish(int what) {
        }
    };

    private void paySuccess() {
//        WeChatBean weChatBean = (WeChatBean)(getIntent().getExtras().getSerializable("weChatBean"));
//        HashMap map = new HashMap();
//        map.put("outTradeNo", weChatBean.gettr);
//        map.put("cardUkid", PayUtil.WXcardUkid);
//        map.put("prepayId", PayUtil.WXprepayId);
//        map.put("tsOperationUkid", PayUtil.WXtsOperationUkid);
//        map.put("registerType", PayUtil.WXregisterType);
//        //                map.put("partnerId", payCreditFragment.WXpartnerId);
//        LogUtils.showLog("outTradeNo    " + PayUtil.WXoutTradeNo + "cardUkid       " + PayUtil.WXcardUkid + "prepayId        " +
//                PayUtil.WXprepayId + "tsOperationUkid          " + PayUtil.WXtsOperationUkid);
//        Request<String> request = NoHttpUtils.getRequest(Constant.WXCHECK, map);
//        requestQueue.add(0, request, onResponseListener);
    }
}